<!--
 * 字典类型管理页面
 * 基于蒜苔系统字典管理设计文档重写，提供完整的字典类型管理功能
 -->

<template>
  <div class="dict-type-list-page">
    <div class="page-header">
      <h1>{{ uiData['list-page-header-string'] }}</h1>
      <p class="page-description">统一管理系统中的各种枚举值、配置项和业务字典数据，提供标准化的数据字典服务</p>
    </div>

    <a-card>
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <div class="search-form">
          <a-form layout="inline" :model="searchParams">
            <a-form-item>
              <a-input 
                v-model:value="searchParams.keyword" 
                :placeholder="uiData['search-placeholder']"
                allow-clear
                @press-enter="handleSearch"
                style="width: 280px"
              >
                <template #prefix>
                  <SearchOutlined />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-select 
                v-model:value="searchParams.status" 
                :placeholder="uiData['status-filter-all']"
                allow-clear
                style="width: 120px"
                @change="handleSearch"
              >
                <a-select-option value="">{{ uiData['status-filter-all'] }}</a-select-option>
                <a-select-option :value="1">{{ uiData['status-filter-enable'] }}</a-select-option>
                <a-select-option :value="0">{{ uiData['status-filter-disable'] }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleSearch">
                  <SearchOutlined /> 搜索
                </a-button>
                <a-button @click="handleReset">
                  <ReloadOutlined /> 重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </div>

      <AnyTable
        ref="itemTable"
        :autoLoad="true"
        :dataLoader="loadItemData"
        :tableColumns="tableColumns"
        :searchParams="searchParams"
        :tableScroll="{ x: 'max-content' }"
        tableRowKey="id"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          getCheckboxProps: (record) => ({
            disabled: record.isSystem === 1,
            name: record.dictName,
          }),
        }"
        @loadComplete="handleLoadComplete"
      >
        <template #tableToolbar>
          <div class="table-toolbar">
            <div class="toolbar-left">
              <a-space :size="12">
                <a-button type="primary" @click="handleAdd">
                  <PlusOutlined /> {{ uiData['add-button-text'] }}
                </a-button>
                <a-button @click="handleBatchDelete" :disabled="selectedRowKeys.length === 0">
                  <DeleteOutlined /> 批量删除
                </a-button>
                <a-button @click="handleBatchStatusChange" :disabled="selectedRowKeys.length === 0">
                  <SwapOutlined /> 批量状态切换
                </a-button>
              </a-space>
            </div>
            <div class="toolbar-right">
              <a-space :size="8">
                <a-tooltip :title="flags.enableMockDataMode ? '当前使用Mock数据模式，点击切换到数据库模式' : '当前使用数据库数据模式，点击切换到Mock模式'">
                  <a-button
                    type="default"
                    :class="flags.enableMockDataMode ? 'data-mode-mock' : 'data-mode-db'"
                    @click="toggleDataMode"
                    size="small"
                  >
                    {{ flags.enableMockDataMode ? '📝 Mock' : '🗄️ 数据库' }}
                  </a-button>
                </a-tooltip>
                <a-button @click="handleRefresh" size="small">
                  <ReloadOutlined /> 刷新
                </a-button>
              </a-space>
            </div>
          </div>
        </template>
        
        <template #tableCell="{ column, record }">
          <template v-if="column.key === 'dictName'">
            <div class="dict-name-cell">
              <span class="dict-name">{{ record.dictName }}</span>
              <a-tag v-if="record.isSystem === 1" color="orange" size="small" class="system-tag">
                {{ uiData['system-builtin-text'] }}
              </a-tag>
            </div>
          </template>
          
          <template v-if="column.key === 'dictType'">
            <a-tag color="blue" class="dict-type-tag">{{ record.dictType }}</a-tag>
          </template>
          
          <template v-if="column.key === 'dictDesc'">
            <a-tooltip :title="record.dictDesc" placement="topLeft">
              <span class="dict-desc">{{ record.dictDesc }}</span>
            </a-tooltip>
          </template>
          
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? uiData['status-enable-text'] : uiData['status-disable-text'] }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'isSystem'">
            <a-tag :color="record.isSystem === 1 ? 'red' : 'green'">
              {{ record.isSystem === 1 ? uiData['system-builtin-text'] : uiData['user-created-text'] }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'sortOrder'">
            <a-input-number 
              :value="record.sortOrder"
              :min="0"
              :max="9999"
              size="small"
              @change="(value) => handleSortOrderChange(record, value)"
              style="width: 80px"
            />
          </template>
          
          <template v-if="column.key === 'createdTime'">
            <span class="time-text">{{ formatDateTime(record.createdTime) }}</span>
          </template>
          
          <template v-if="column.key === 'updatedTime'">
            <span class="time-text">{{ formatDateTime(record.updatedTime) }}</span>
          </template>
          
          <template v-if="column.key === 'op'">
            <a-space size="small">
              <a-tooltip title="管理字典数据">
                <a-button type="link" size="small" @click="handleManageDictData(record)" class="data-manage-btn">
                  <DatabaseOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip :title="uiData['view-button-text']">
                <a-button type="link" size="small" @click="handleView(record)">
                  <EyeOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip :title="record.isSystem === 1 ? '系统内置字典不允许编辑' : uiData['edit-button-text']">
                <a-button 
                  type="link" 
                  size="small" 
                  @click="handleEdit(record)" 
                  :disabled="record.isSystem === 1"
                >
                  <EditOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip :title="record.isSystem === 1 ? uiData['system-dict-delete-error'] : uiData['delete-button-text']">
                <a-button 
                  type="link" 
                  size="small"
                  danger 
                  @click="handleDelete(record)" 
                  :disabled="record.isSystem === 1"
                >
                  <DeleteOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip :title="record.status === 1 ? '点击禁用' : '点击启用'">
                <a-button 
                  type="link" 
                  size="small"
                  @click="handleStatusToggle(record)"
                  :disabled="record.isSystem === 1"
                >
                  <PoweroffOutlined :style="{ color: record.status === 1 ? '#52c41a' : '#ff4d4f' }" />
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </AnyTable>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <SysDictTypeAddOrEditModal
      ref="addOrEditModalRef" 
      :callbackFunc="handleRefresh"
    />
    
    <!-- 详情查看弹窗 -->
    <SysDictTypeDetailModal ref="detailModalRef" @edit="handleEditFromDetail" />
  </div>
</template>

<style scoped>
.dict-type-list-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #262626;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.search-section {
  margin-bottom: 16px;
}

.search-form {
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar-left {
  flex: 1;
}

.toolbar-right {
  flex-shrink: 0;
}

.dict-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dict-name {
  font-weight: 500;
  color: #1890ff;
}

.system-tag {
  margin-left: 4px;
}

.dict-type-tag {
  font-family: 'Courier New', monospace;
}

.dict-desc {
  display: block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.data-manage-btn {
  color: #722ed1 !important;
}

.time-text {
  color: #666;
  font-size: 12px;
}

/* 数据模式按钮样式 */
.data-mode-mock {
  border-color: #ff7a00 !important;
  color: #ff7a00 !important;
  background-color: #fff7e6 !important;
}

.data-mode-mock:hover {
  border-color: #ff7a00 !important;
  color: #ff7a00 !important;
  background-color: #ffefde !important;
}

.data-mode-db {
  border-color: #52c41a !important;
  color: #52c41a !important;
  background-color: #f6ffed !important;
}

.data-mode-db:hover {
  border-color: #52c41a !important;
  color: #52c41a !important;
  background-color: #eefdde !important;
}

/* 状态开关样式 */
:deep(.ant-switch-checked) {
  background-color: #52c41a;
}

:deep(.ant-switch-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 表格行样式 */
:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

/* 系统内置行样式 */
:deep(.ant-table-tbody > tr.system-row > td) {
  background-color: #fff7e6;
}

:deep(.ant-table-tbody > tr.system-row:hover > td) {
  background-color: #ffefde;
}
</style>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { 
  PlusOutlined, 
  SearchOutlined, 
  ReloadOutlined,
  DatabaseOutlined,
  EditOutlined,
  EyeOutlined,
  DeleteOutlined,
  PoweroffOutlined,
  SwapOutlined
} from '@ant-design/icons-vue';
import { apiSysDictTypeFetchList, apiSysDictTypeDelete, apiSysDictTypeUpdateStatus, apiSysDictTypeUpdateSortOrder } from "./api";
import { tableColumns, uiData, flags } from "./data";
import SysDictTypeDetailModal from "./detail.vue";
import SysDictTypeAddOrEditModal from "./add-or-edit.vue";
import type { SysDictType } from "./types";

const { $AnyMessageBox } = getCurrentInstance()!.appContext.config.globalProperties;
const router = useRouter();

// 搜索参数
const searchParams = reactive<{
  keyword?: string;
  status?: number | string;
}>({});

// 页面状态
const selectedRowKeys = ref<number[]>([]);
const loading = ref(false);

// 组件引用
const itemTable = ref();
const addOrEditModalRef = ref();
const detailModalRef = ref<InstanceType<typeof SysDictTypeDetailModal>>();

// 加载数据
async function loadItemData(params: any) {
  try {
    // 处理搜索参数
    const searchData = { ...params };
    
    // 关键词搜索转换为具体字段搜索
    if (searchParams.keyword) {
      searchData.dictName = searchParams.keyword;
      searchData.dictType = searchParams.keyword;
    }
    
    // 状态筛选
    if (searchParams.status !== undefined && searchParams.status !== '') {
      searchData.status = Number(searchParams.status);
    }
    
    const response = await apiSysDictTypeFetchList(searchData);
    // 处理不同的响应格式
    if (response.success && response.data) {
      return response.data;
    } else if (response.data) {
      return response.data;
    } else {
      return response;
    }
  } catch (error) {
    console.error('加载字典类型数据失败:', error);
    $AnyMessageBox.message.error('加载数据失败');
    return { records: [], total: 0 };
  }
}

// 加载完成回调
function handleLoadComplete() {
  console.log('字典类型数据加载完成');
}

// 行选择处理
function onSelectChange(selectedKeys: number[]) {
  selectedRowKeys.value = selectedKeys;
}

// 搜索和重置
function handleSearch() {
  itemTable.value?.refreshTable(true);
}

function handleReset() {
  Object.keys(searchParams).forEach(key => {
    delete searchParams[key as keyof typeof searchParams];
  });
  itemTable.value?.resetTable();
}

// 切换数据模式
function toggleDataMode() {
  flags.enableMockDataMode = !flags.enableMockDataMode;
  $AnyMessageBox.message.info(
    flags.enableMockDataMode ? '已切换到Mock数据模式' : '已切换到数据库模式'
  );
  handleRefresh();
}

// 刷新表格
function handleRefresh() {
  itemTable.value?.refreshTable();
}

// CRUD操作
function handleAdd() {
  addOrEditModalRef.value?.showAdd();
}

function handleEdit(item: SysDictType) {
  if (item.isSystem === 1) {
    $AnyMessageBox.message.warning('系统内置字典类型不允许编辑');
    return;
  }
  addOrEditModalRef.value?.showEdit(item.id);
}

function handleView(item: SysDictType) {
  detailModalRef.value?.openModal(item);
}

// 从详情弹窗触发的编辑操作
function handleEditFromDetail(item: SysDictType) {
  addOrEditModalRef.value?.showEdit(item.id);
}

function handleDelete(item: SysDictType) {
  if (item.isSystem === 1) {
    $AnyMessageBox.message.warning(uiData['system-dict-delete-error']);
    return;
  }
  
  $AnyMessageBox.confirmDanger(
    uiData['confirm-delete-title'],
    `确认删除字典类型"${item.dictName}"？删除后该类型下的所有字典数据也将被删除，此操作不可恢复！`,
    async () => {
      try {
        loading.value = true;
        await apiSysDictTypeDelete(item.id);
        $AnyMessageBox.message.success(uiData['delete-success']);
        handleSearch();
      } catch (error) {
        console.error('删除字典类型失败:', error);
        $AnyMessageBox.message.error('删除失败');
      } finally {
        loading.value = false;
      }
    }
  );
}

// 批量操作
function handleBatchDelete() {
  if (selectedRowKeys.value.length === 0) {
    $AnyMessageBox.message.warning('请选择要删除的数据');
    return;
  }
  
  $AnyMessageBox.confirmDanger(
    '批量删除确认',
    `确认删除选中的 ${selectedRowKeys.value.length} 个字典类型？此操作不可恢复！`,
    async () => {
      try {
        loading.value = true;
        // 这里应该调用批量删除API，暂时用循环删除
        for (const id of selectedRowKeys.value) {
          await apiSysDictTypeDelete(id);
        }
        $AnyMessageBox.message.success('批量删除成功');
        selectedRowKeys.value = [];
        handleSearch();
      } catch (error) {
        console.error('批量删除失败:', error);
        $AnyMessageBox.message.error('批量删除失败');
      } finally {
        loading.value = false;
      }
    }
  );
}

function handleBatchStatusChange() {
  if (selectedRowKeys.value.length === 0) {
    $AnyMessageBox.message.warning('请选择要操作的数据');
    return;
  }
  
  $AnyMessageBox.confirm(
    '批量状态切换',
    `确认切换选中的 ${selectedRowKeys.value.length} 个字典类型的状态？`,
    async () => {
      try {
        loading.value = true;
        // 这里应该调用批量状态切换API，暂时用循环处理
        for (const id of selectedRowKeys.value) {
          // 获取当前状态并切换
          const currentItem = itemTable.value?.getTableData()?.find((item: SysDictType) => item.id === id);
          if (currentItem && currentItem.isSystem !== 1) {
            const newStatus = currentItem.status === 1 ? 0 : 1;
            await apiSysDictTypeUpdateStatus(id, newStatus);
          }
        }
        $AnyMessageBox.message.success('批量状态切换成功');
        selectedRowKeys.value = [];
        handleSearch();
      } catch (error) {
        console.error('批量状态切换失败:', error);
        $AnyMessageBox.message.error('批量状态切换失败');
      } finally {
        loading.value = false;
      }
    }
  );
}

// 状态切换
async function handleStatusToggle(item: SysDictType) {
  if (item.isSystem === 1) {
    $AnyMessageBox.message.warning('系统内置字典类型不允许修改状态');
    return;
  }
  
  try {
    loading.value = true;
    const newStatus = item.status === 1 ? 0 : 1;
    await apiSysDictTypeUpdateStatus(item.id, newStatus);
    item.status = newStatus;
    $AnyMessageBox.message.success(uiData['status-update-success']);
  } catch (error) {
    console.error('更新状态失败:', error);
    $AnyMessageBox.message.error('状态更新失败');
  } finally {
    loading.value = false;
  }
}

// 更新排序
async function handleSortOrderChange(item: SysDictType, value: number | null) {
  if (value === null || value === item.sortOrder) {
    return;
  }
  
  try {
    await apiSysDictTypeUpdateSortOrder(item.id, value);
    item.sortOrder = value;
    $AnyMessageBox.message.success('排序更新成功');
    // 重新加载数据以显示新的排序
    setTimeout(() => {
      handleSearch();
    }, 500);
  } catch (error) {
    console.error('更新排序失败:', error);
    $AnyMessageBox.message.error('排序更新失败');
  }
}

// 管理字典数据
function handleManageDictData(item: SysDictType) {
  // 跳转到字典数据管理页面，并传递字典类型参数
  router.push({
    path: '/admin/miaoma/sysdictdata/list',
    query: {
      dictType: item.dictType,
      dictTypeName: item.dictName,
      dictTypeId: item.id
    }
  });
}

// 格式化日期时间
function formatDateTime(dateTime: string | undefined): string {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}
</script>